<template>
  <div>
    <!--    面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right" >
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--    卡片区域-->
    <el-card>
      <!--     搜索与添加区域 -->
      <el-row :gutter="20" >
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加商品</el-button>
        </el-col>
      </el-row>
      <!--     用户列表区域 -->
      <el-table
        :data="goodslist"
        style="width: 100%"
        border
        stripe>
        <!-- 添加索引列 直接把type属性设置成index即可-->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="gdName" label="商品名称"></el-table-column>
        <el-table-column prop="gdPrice" label="商品价格"></el-table-column>
        <el-table-column prop="gdCount" label="商品数量"></el-table-column>
        <el-table-column prop="gdIntroduce" label="商品介绍"></el-table-column>
        <el-table-column prop="cateName" label="商品类别"></el-table-column>
        <el-table-column prop="depName" label="商品分区"></el-table-column>
        <el-table-column label="是否需要进货">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.gdCount <= '10'">是</el-tag>
            <el-tag v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!--          编辑按钮-->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.gdId)">修改</el-button>
            <!--          删除按钮  -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="showdDeleteTip(scope.row.gdId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--   添加用户对话框区域 -->
    <el-dialog
      title="添加商品"
      :visible.sync="addDialogVisible"
      width="40%"
      @close="addFormClosed">
      <!--      内容主体区域-->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item label="商品名称" prop="gdName">
          <el-input v-model="addForm.gdName"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="gdPrice">
          <el-input v-model="addForm.gdPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="gdCount">
          <el-input v-model="addForm.gdCount"></el-input>
        </el-form-item>
        <el-form-item label="商品介绍" prop="gdIntroduce">
          <el-input v-model="addForm.gdIntroduce"></el-input>
        </el-form-item>
        <el-form-item label="商品分区/类" prop="cateId">
          <el-cascader
            v-model="value"
            :options="depcategoodsList"
            :props="cascaderProps"
            @change="selectedHandleChange"
            clearable></el-cascader>
        </el-form-item>
      </el-form>
      <!--      底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addGoods">确 定</el-button>
      </span>
    </el-dialog>
    <!--    修改用户对话框区域-->
    <!--    :before-close="handleClose"-->
    <el-dialog
      title="修改商品信息"
      :visible.sync="editDialogVisible"
      width="40%"
      @close="editFormClosed">
      <!--      内容主体区域-->
      <el-form ref="editFormRef" :model="editForm" :rules="addFormRules" label-width="100px">
        <el-form-item label="商品名称" prop="gdName" :disabled="true" :placeholder="editForm.gdName">
          <el-input v-model="editForm.gdName"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="gdPrice" :placeholder="editForm.gdPrice">
          <el-input v-model="editForm.gdPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="gdCount" :placeholder="editForm.gdCount">
          <el-input v-model="editForm.gdCount"></el-input>
        </el-form-item>
        <el-form-item label="商品介绍" prop="gdIntroduce" :placeholder="editForm.gdIntroduce">
          <el-input v-model="editForm.gdIntroduce"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="cateId">
          <el-cascader
            v-model="modifyvalue"
            :options="depcategoodsList"
            :props="cascaderProps"
            @change="selectedHandleChange"
            clearable></el-cascader>
        </el-form-item>
      </el-form>
      <!--      底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editGoodsInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import qs from 'qs'
import ImgUpload from '../ImgUpload.vue'
export default {
  name: 'Goods',
  components: {ImgUpload},
  data () {
    // 验证邮箱的校验规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      let regEmail = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
      if (regEmail.test(value)) return cb()
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的校验规则
    var checkMobile = (rule, value, cb) => {
      let regMobile = /^1[3|4|5|7|8][0-9]\d{8}$/
      if (regMobile.test(value)) return cb()
      cb(new Error('请输入合法的手机'))
    }
    return {
      // 级联选择器选中的数组
      value: [],
      modifyvalue: [],
      // cateOptions: [],
      // departOptions: [],
      // checkedDatesById: [],
      // checkedDates: [],
      depcategoodsList: [],
      cascaderProps: {
        // value指定你所选择的实际是哪个属性
        value: 'value',
        // label指定你所选择的显示出来的是哪个属性
        label: 'label',
        // children指定父子之间嵌套的是哪个属性
        children: 'children',
        expandTrigger: 'hover'
      },
      Dates: ['星期一上午8:00-12:00', '星期一下午13:00-18:00', '星期二上午8:00-12:00', '星期二下午13:00-18:00', '星期三上午8:00-12:00', '星期三下午13:00-18:00', '星期四上午8:00-12:00', '星期四下午13:00-18:00', '星期五上午8:00-12:00', '星期五下午13:00-18:00'],
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      goodslist: [],
      total: 0,
      addDialogVisible: false,
      // 控制编辑用户对话框得显示与否
      editDialogVisible: false,
      // 控制分配角色对话框的显示与否
      setRoleDialogVisible: false,
      // 添加用户的表单数据对象
      addForm: {
        gdName: '',
        gdPrice: '',
        gdCount: '',
        gdIntroduce: '',
        cateId: '',
        depId: ''
      },
      userInfo: {},
      // 添加表单的验证规则对象
      addFormRules: {
        // 用户名的验证规则
        gdName: [
          {
            required: true, message: '请输入商品名称', trigger: 'blur'
          }
        ],
        gdPrice: [
          {
            required: true, message: '请输入商品价格', trigger: 'blur'
          }
        ],
        gdCount: [
          {
            required: true, message: '请输入商品数量', trigger: 'blur'
          }
        ],
        cateId: [
          {
            required: true, message: '请输入分类', trigger: 'blur'
          }
        ],
        depId: [
          {
            required: true, message: '请输入分区', trigger: 'blur'
          }
        ]
      },
      // 查询用户信息保存得对象
      editForm: {}
    }
  },
  created () {
    this.getGoodsList()
    this.getDepCateGoodsList()
  },
  methods: {
    getDepCateGoodsList () {
      this.$axios.get('category/allList', {params: {type: 2}})
        .then(resp => {
          if (resp.data.status !== 200) { this.$message.error('获取allList失败') }
          this.depcategoodsList = resp.data.data
          console.log(this.depcategoodsList)
          this.$message.success('获取allList成功')
        })
    },
    selectedHandleChange (jiedian) {
      console.log('jiedian')
      console.log(jiedian)
      console.log('value')
      console.log(this.value)
      this.addForm.depId = this.value[0]
      this.addForm.cateId = this.value[1]
      console.log(this.getGoodsList)
    },
    getGoodsList () {
      this.$axios.get('goods', {params: this.queryInfo})
        .then(resp => {
          if (resp && resp.data.status !== 200) {
            // return this.$message.error('获取商品列表失败!')
          }
          this.goodslist = resp.data.data.data
          this.total = resp.data.data.totalpage
          // this.$message.success('获取商品列表成功!')
        })
    },
    // 监听每页显示数量变化函数
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      // 每页显示数量变化后 重新请求用户列表
      this.getGoodsList()
    },
    // 监听当前页码变化函数
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getGoodsList()
    },
    // 监听 添加用户对话框的关闭 事件
    addFormClosed () {
      // 关闭时 表单重置
      this.$refs.addFormRef.resetFields()
    },
    addGoods () {
      // validate 对整个表单进行验证 参数为一个回调函数 回调函数得第一个参数为验证是否成功变量
      this.$refs.addFormRef.validate(valid => {
        // 若验证不通过，则什么也不做 直接返回
        if (!valid) return
        // 发起网络请求 添加新用户
        this.$axios
          .post('goods', qs.stringify(this.addForm), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
          .then(resp => {
            console.log(resp.data)
            if (resp.data.status !== 200) this.$message.error('添加商品失败!')
            this.addDialogVisible = false
            this.getGoodsList()
            this.$message.success('添加商品成功')
          })
      })
    },
    // 这里显示原来的用户表单数据，不建议从本地scope.row获取 使用后端根据id获取用户信息接口
    showEditDialog (id) {
      this.$axios
        .get('goods/' + id)
        .then(resp => {
          if (resp.data.status !== 200) this.$message.error('获取商品失败!')
          console.log(resp.data.data)
          this.editForm = resp.data.data
          this.modifyvalue[0] = this.editForm.depId
          this.modifyvalue[1] = this.editForm.cateId
          // 显示编辑对话框
          // this.$refs.iimgUpload.fileList = [{name: 'url', url: this.editForm.epPhoto}]
          this.editDialogVisible = true
        })
    },
    // 监听 编辑用户对话框的 关闭事件
    editFormClosed () {
      this.$refs.editFormRef.resetFields()
    },
    editGoodsInfo () {
      // validate 对整个表单进行验证 参数为一个回调函数 回调函数得第一个参数为验证是否成功变量
      this.$refs.editFormRef.validate(valid => {
        // 若验证不通过，则什么也不做 直接返回
        if (!valid) return
        // 发起网络请求 修改用户信息
        this.editForm.depId = this.modifyvalue[0]
        this.editForm.cateId = this.modifyvalue[1]
        this.$axios
          .put('goods', qs.stringify(this.editForm), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
          .then(resp => {
            console.log(resp.data)
            if (resp.data.status !== 200) this.$message.error('更新商品信息失败!')
            this.editDialogVisible = false
            // 重新获取用户列表数据
            this.getGoodsList()
            this.$message.success('修改商品信息成功')
          })
      })
    },
    showdDeleteTip (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios
          .delete('goods/' + id)
          .then(resp => {
            console.log(resp.data)
            if (resp.data.status !== 200) return this.$message.error('删除失败')
            this.getGoodsList()
          })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang = "less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 12px;
}
.el-table {
  margin-top: 15px;
  margin-bottom: 15px;
  font-size: 13px;
}
.image{
  width: 60px;
  height: 70px;
}
</style>
